package com.huimin.merchant.common.intercept;

import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.ErrorCode;
import com.huiminpay.common.cache.domain.RestErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理程序
 * <p>
 * ControllerAdvice和ExceptionHandler结合可以捕获Controller抛出的异常，
 * 根据异常处理流程，Service和持久层最终都会抛给Controller，所以此方案可以实现全局异常捕获，
 * 异常被捕获到即可格式为前端要的信息格式响应给前端。
 *
 * @author amx
 * @date 2020/12/2 7:07
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


	@ExceptionHandler
	@ResponseBody
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public RestErrorResponse processException(HttpServletRequest request,
	                                          HttpServletResponse response,
	                                          Exception exception) {

		RestErrorResponse restErrorResponse = new RestErrorResponse();
		// 如果是自定义异常，则直接取出异常信息
		if (exception instanceof BusinessException) {
			BusinessException businessException = (BusinessException) exception;
			ErrorCode errorCode = businessException.getErrorCode();

			restErrorResponse.setErrCode(errorCode.getCode());
			restErrorResponse.setErrMessage(errorCode.getDesc());
			// 否则报未知异常
		} else {
			CommonErrorCode errorCode = CommonErrorCode.UNKOWN;
			restErrorResponse.setErrCode(errorCode.getCode());
			restErrorResponse.setErrMessage(errorCode.getDesc());
			log.error("异常如下:{ }", exception);
		}

		return restErrorResponse;
	}

}
